package com.kx.springsecurity.service;

import com.kx.springsecurity.domain.Menu;
import com.kx.springsecurity.domain.Role;
import com.kx.springsecurity.domain.User;
import com.kx.springsecurity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 我们已经告诉 spring 我们每个地址需要什么权限了,现在我们需要告诉 spring 当前登录的用户具有什么权限
 * 因为登陆操作是我们自己定义的,spring 本身不知道,所以 spring 提供了一个接口,让我们实现,我们在内部返回当前登录的用户信息
 * spring 会接管登录地址,登录的密码判断,权限,角色判断等等
 *
 * @ClassName MyUserService
 * @Author Sun
 * @Date 2021/5/25 19:45
 */
@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    /**
     *通过用户名来加载用户
     * @param username 就是用户登录的时候写的用户名,我们需要根据这个用户查询到用户的信息,然后返回数据
     * @return  当前登录的用户信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询出来的用户信息
        User user = userMapper.getUserByName(username);
        if (user == null) {
            return null;
        }
        //保存用户所有权限的集合
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        List<Role> roles = user.getRoleList();
        for (Role role : roles) {
            //获取每一个角色
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + role.getRolename());
            authorityList.add(simpleGrantedAuthority);//保存每一个角色名
            List<Menu> menus = role.getMenuList();
            for (Menu menu : menus) {
                //获取每个角色的权限
                String permisson = menu.getPermisson();
                //保存每个角色的权限信息
                authorityList.add(new SimpleGrantedAuthority(permisson));
            }
        }
        //spring security 中提供的User类
        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorityList);
        return user1;
    }
}
